package custom.kyletterfilter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class KyLetterfilter extends View{
	private custom.kyletterfilter.ParamsCreator paramsCreator = new custom.kyletterfilter.ParamsCreator(this.getContext());
	private int selfWidth;
	private int selfHeight;
	
	private List<InnerWrapper> wrappers;
	private Paint paint = new Paint();
	
	//字母背景颜色
	private int normalBgColor = 0x00FFFFFF;//正常情况下的
	private int selectedBgColor = 0xB0619BBD;//选中的
	//监听器
	private custom.kyletterfilter.OnLetterfilterListener onLetterfilterListener;
	
	public KyLetterfilter(Context context) {
		super(context);
	}
	public KyLetterfilter(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	public KyLetterfilter(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		this.selfWidth = paramsCreator.getWidth();
		this.selfHeight = MeasureSpec.getSize(heightMeasureSpec);
		setMeasuredDimension(this.selfWidth, this.selfHeight);
	}
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawColor(this.normalBgColor);
		createWrappers();
		drawLetter(canvas);
	}
	/**
	 * 创建wrappers
	 */
	private void createWrappers(){
		if(this.wrappers != null)
			return ;
		String[] letterArr = {"#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z","*"};
		this.wrappers = new ArrayList<InnerWrapper>();
		int letterCount = 28;//字符个数(26个英文字母+一个#和*)
		int wrapperHeight = this.selfHeight/letterCount;//每个字母占区域的高度
		int top = 0;
		for(int i = 0; i<letterCount; i++){
			int textColor = 0xFF525252;
			int bottom = top + wrapperHeight;
			InnerWrapper wrapper = new InnerWrapper(0, top, this.selfWidth, bottom, letterArr[i], textColor);
			this.wrappers.add(wrapper);
			top += wrapperHeight;
		}
	}
	/**
	 * 开始画
	 */
	private void drawLetter(Canvas canvas){
		paint.setTextSize(this.paramsCreator.getTextSize());
		FontMetricsInt fontMetrics = paint.getFontMetricsInt();
		int txtHeight = fontMetrics.bottom - fontMetrics.ascent;
		for(InnerWrapper wrapper : this.wrappers){
			//画背景
			RectF rectF = new RectF(wrapper.left, wrapper.top, wrapper.right , wrapper.bottom);
			if(wrapper.selected)
				paint.setColor(this.selectedBgColor);
			else
				paint.setColor(this.normalBgColor);
			paint.setStyle(Paint.Style.FILL);
			canvas.drawRoundRect(rectF, this.paramsCreator.getRadius(), this.paramsCreator.getRadius(), paint);	
			//画文字
			paint.setColor(wrapper.textColor);
			paint.setStyle(Paint.Style.STROKE);
			int txtWidth = (int)this.paint.measureText(wrapper.letter);
			canvas.drawText(wrapper.letter, wrapper.left + ((wrapper.right-wrapper.left)/2-txtWidth/2), wrapper.top+((wrapper.bottom-wrapper.top)-txtHeight)/2-fontMetrics.ascent, paint);	
		}
	}
	/**
	 * 触碰事件
	 */
	@Override
    public boolean onTouchEvent(MotionEvent event) {    	
    	try {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				allowSetCurrent = false;
				downTouch((int)event.getX(), (int)event.getY());
			    break;            
			case MotionEvent.ACTION_MOVE:    
				moveTouch((int)event.getX(), (int)event.getY());
			    break;            
			case MotionEvent.ACTION_UP:
				upTouch();
				allowSetCurrent = true;
			    break; 		
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return true;
    }
	/**
	 * 处理手指按下事件
	 */
	private void downTouch(int x, int y){
		try {
			if(this.onLetterfilterListener != null)
				this.onLetterfilterListener.start();
			InnerWrapper oldWrapper = getSelectedWrapper();
			InnerWrapper touchedWrapper = getTouchedWrapper(x, y);
			if(oldWrapper != touchedWrapper){
				if(this.onLetterfilterListener != null){
					this.onLetterfilterListener.letterChanged(touchedWrapper.letter);
				}
				resetSelectedFlag();
				touchedWrapper.selected = true;
				this.invalidate();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 处理手指滑动事件
	 */
	private void moveTouch(int x, int y){
		InnerWrapper oldWrapper = getSelectedWrapper();
		InnerWrapper touchedWrapper = getTouchedWrapper(x, y);
		if(oldWrapper != touchedWrapper){
			if(this.onLetterfilterListener != null){
				this.onLetterfilterListener.letterChanged(touchedWrapper.letter);
			}
			resetSelectedFlag();
			touchedWrapper.selected = true;
			this.invalidate();
		}
	}
	/**
	 * 处理手指抬起事件
	 */
	private void upTouch(){
		resetSelectedFlag();
		this.invalidate();
		if(this.onLetterfilterListener != null)
			this.onLetterfilterListener.end();
	}
	/**
	 * 获得触碰点的wrapper
	 */
	private InnerWrapper getTouchedWrapper(int x, int y){
		for(InnerWrapper wrapper : wrappers){
			if(x>=wrapper.left && x <= wrapper.right){
				if(y>=wrapper.top && y<=wrapper.bottom){
					//System.out.println("LetterfilterWidget downClick:单击了"+wrapper.letter);
					return wrapper;
				}
			}
		}
		return null;
	}
	/**
	 * 重置选中标记
	 */
	private void resetSelectedFlag(){
		for(InnerWrapper wrapper : this.wrappers){
			wrapper.selected = false;
		}
	}
	/**
	 * 获得被选中的wrapper
	 */
	private InnerWrapper getSelectedWrapper(){
		for(InnerWrapper wrapper : this.wrappers){
			if(wrapper.selected)
				return wrapper;
		}
		return null;
	}
	/**
	 * 设置当前字母(供外部调用)
	 */
	private boolean allowSetCurrent = true;//是否允许从外界修改letter
	public void setCurrent(String letter){
		if(!allowSetCurrent)
			return ;
		if(this.wrappers == null)
			return ;
		InnerWrapper newWrapper = null;
		for(InnerWrapper wrapper : this.wrappers){
			if(wrapper.letter.equals(letter)){
				newWrapper = wrapper;
				break;
			}
		}
		if(newWrapper == null)//不支持这个字母
			return ;
		InnerWrapper oldWrapper = getSelectedWrapper();
		if(oldWrapper != null && oldWrapper.letter.equals(letter))//当前已经是这个字母了
			return ;
		resetSelectedFlag();
		newWrapper.selected = true;
		this.invalidate();
	}
	/**
	 * 内部封装类
	 */
	private class InnerWrapper{
		int left;
		int top;
		int right;
		int bottom;
		String letter;//字母
		int textColor;//字母颜色
		boolean selected = false;//是否是被选中，即当前的
		public InnerWrapper(int left, int top, int right, int bottom, String letter, int textColor){
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
			this.letter = letter;
			this.textColor = textColor;
		}
	}

	
	
	

	
	public void setNormalBgColor(int normalBgColor) {
		this.normalBgColor = normalBgColor;
	}
	public void setSelectedBgColor(int selectedBgColor) {
		this.selectedBgColor = selectedBgColor;
	}
	
	public void setOnLetterfilterListener(
			custom.kyletterfilter.OnLetterfilterListener onLetterfilterListener) {
		this.onLetterfilterListener = onLetterfilterListener;
	}

}

